/**
 * 
 */
package com.gome.gop.common;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 字符串相关的共通类
 * 
 * @author Administrator
 *
 */
public final class StringUtil {

    private static Logger logger = LoggerFactory.getLogger(StringUtil.class);

    /**
	 * Excel文件扩展名
	 */
	public static final String EXCEL_EXTENSION = ".xls";
	
	/**
	 * 构造函数
	 */
	private StringUtil() {
	}
	
	/**
	 * 根据查询条件中DataGrid中的title转换为相应的字段
	 * @param titleAndColArr
	 * 		  DataGrid中的title和字段对应数组
	 * @param conditions
	 * 		      前台传入的查询条件
	 * @return 转换后的条件
	 */
	public static String titleTransToField(String[] titleAndColArr, String conditions) {
		String titleAndColStr = "";
		
		if (null != conditions && !"".equals(conditions)) {
			for (int i=0; i<titleAndColArr.length; i++) {
				titleAndColStr = titleAndColArr[i];
				conditions = conditions.replaceAll(titleAndColStr.split("-")[0], titleAndColStr.split("-")[1]);
			}
			conditions = "(" + conditions +")";
		}
		return conditions;
	}
	
	/**
	 * 获取一个随机的UUID32位
	 * @return 32位UUID
	 */
	public static String getRandomUUID32(){
		String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
		return uuid;
	}
	
    /**
     * 导出数据到Excel文件中. 
     * @param dataList          数据数组
     * @param outputStream      输出流
     * @throws Exception        异常
     */
    public static void export(List<?> dataList, OutputStream outputStream) throws Exception {
        try {
			if (dataList == null) {
				return;
			} else {
				if (dataList.get(0) == null) {
					return;
				}
			}

			// 创建Workbook(07版)
			HSSFWorkbook workbook = new HSSFWorkbook();

			// 根据第一条记录，获取对象所有要输出的字段信息
			Object first = dataList.get(0);
			Class<?> objClass = first.getClass();
			List<FieldInfo> actuFields = new ArrayList<FieldInfo>();
			Method[] methods = objClass.getMethods();
			for (Method method : methods) {
				ExcelColumn anno = method.getAnnotation(ExcelColumn.class);
				if (anno != null) {
					FieldInfo info = new FieldInfo();
					info.index = anno.index();
					info.title = anno.title();
					info.onlyDate = anno.onlyDate();
					info.type = method.getReturnType();
					info.method = method;
					actuFields.add(info);
				}
			}

			// 根据字段的注解中的Index，进行排序
			Collections.sort(actuFields, new Comparator<FieldInfo>() {
				public int compare(FieldInfo field1, FieldInfo field2) {
					return field1.index - field2.index;
				}
			});

			int sheetIndex = 1;
			int rowIndex = 0;
			
			// 输出字段的标题
			Sheet sheet = workbook.createSheet("Sheet"+sheetIndex);
			Row row = sheet.createRow(rowIndex);
			for (int i = 0; i < actuFields.size(); i++) {
				row.createCell(i).setCellValue(actuFields.get(i).title);
			}

			// 输出记录数据(每6万条分割)
			for (int j = 0; j < dataList.size(); j++) {
				if(j>0 && j % 60000 == 0) {
					sheetIndex++;
					sheet = workbook.createSheet("Sheet"+sheetIndex);
					rowIndex = 0;
					row = sheet.createRow(rowIndex);
					for (int i = 0; i < actuFields.size(); i++) {
						row.createCell(i).setCellValue(actuFields.get(i).title);
					}
				}
				
				rowIndex++;
				Object data = dataList.get(j);
				row = sheet.createRow(rowIndex);
				for (int k = 0; k < actuFields.size(); k++) {
				    if (logger.isDebugEnabled()){
                        logger.debug("文件解析. k=[{}]，methodName =[{}],data=[{}]",k,actuFields.get(k).method.getName(), JSONObject.toJSONString(data));
                        logger.debug("",k);
                    }
					FieldInfo field = actuFields.get(k);
					Object val = field.method.invoke(data);
					if (val != null) {
						if (field.type == Date.class) {
							// 日期类型，特殊处理
							if (field.onlyDate) {
								row.createCell(k)
										.setCellValue(
												new SimpleDateFormat("yyyy-MM-dd").format((Date) val));
							} else {
								row.createCell(k)
										.setCellValue(
												 new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date) val));
							}
						} else {
							// 其它类型，直接输出
							row.createCell(k).setCellValue(val.toString());
						}
					}
				}
			}
            
            workbook.write(outputStream);
            outputStream.close();
        } catch (Exception e) {
            throw e;
        }
    }
   static class FieldInfo {
        /**
         * 列输出顺序
         */
        public int index;
        
        /**
         * 列输出标题
         */
        public String title;
        
        /**
         * 方法
         */
        public Method method;
        
        /**
         * 字段类型
         */
        public Class<?> type;
        
        /**
         * 是否只显示日期
         */
        public boolean onlyDate = false;
    }

	public static String getCode5() {
		String code = String.valueOf((int) ((Math.random() * 9 + 1) * 10000));
		return code;
	}
}
